#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import sys
import random
from Dices import *

class plotGenerator(object):

  __version__ = '0.0.3'
  __author__ = 'Bartosz Bubak <bartosz.bubak@gmail.com>'

  def __init__(self):
    pass

  def replaceFromFile(self, filename):
    m = re.search('(?<=\$\{).*?\}', filename)
    name = m.group(0)[:-1]
    buffer = open(name,'rb').readlines()
    result = self.parseLine(re.sub('\n|\r', '', random.choice(buffer)))
    return result

  def diceThrow(self, dice):  
    d = Dice(dice[1:])
    d.throw()
    return d.getSum()

  def parseLine(self, line):
    result = ''
    m = re.split('\s*', line)
    for x in m:
      if re.match('^\$\{.*\}', x):
        result += '%s ' % self.replaceFromFile(x)
        #result += u'%s ' % self.replaceFromFile(x).decode('cp1250')
      elif re.match('\$(\d+){0,}([dDkK])(\d+)', x):
        result += '%d ' % self.diceThrow(x)
      else:
        result += '%s ' % x
    return result

if __name__ == "__main__":
  pg = plotGenerator()
  print pg.parseLine('$2k100 lat temu ${kto.txt} ${kogo.txt} ${co_robi.txt} ${dlaczego.txt}')
